<?php

namespace App\Http\Controllers\Common;

use App\Http\Controllers\BaseController;
use App\Models\Common\ConfigModel;
use App\Models\Common\FsCompanyModel;
use App\Models\Common\FsCompanyUserMappingModel;
use App\Models\Common\FsOrganizationModel;
use Guanguans\Notify\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RobotController extends BaseController
{
    public function webHockCardMessage(Request $request)
    {
        $token  = $request->get('token');
        $secret = $request->get('secret');
        $card   = $request->get('card');

        $this->validate($request, [
            'token'  => 'required|string',
            'secret' => 'required|string',
            'card'   => 'required|string',
        ]);

        $data = Factory::feiShu()
                       ->setToken($token)
                       ->setSecret($secret)
                       ->setMessage(new \Guanguans\Notify\Messages\FeiShu\CardMessage(json_decode($card, true)))
                       ->send();

        return $this->success($data);
    }

    public function getFsConfigByPlatformNameFeiShuId(Request $request)
    {
        $platformName = $request->get('platformName');
        $feishuId     = $request->get('feishuId');

        $this->validate($request, [
            'platformName' => 'required|string',
            'feishuId'     => 'required|string',
        ]);

        $fsCompanyId = FsCompanyUserMappingModel::query()->where('feishuId', $feishuId)->value('fsCompanyId');
        if (!$fsCompanyId) {
            return $this->fail(400, '不存在的feishuId');
        }

        $orgId = (string)FsCompanyModel::query()->where('id', $fsCompanyId)->value('organizationId');
        if (!$orgId) {
            return $this->fail(400, '不存在的orgId');
        }

        $data = ConfigModel::getFsConfigByPlatformNameOrgId($platformName, $orgId);

        return $this->success($data);
    }

    public function getFeiShuIdByUserIdsExt(Request $request)
    {
        $userIds = $request->get('userIds');

        $this->validate($request, [
            'userIds' => 'required|array'
        ]);

        $userIdImp = implode(',', $userIds);

        $data = DB::select("SELECT f.feishuId, f.rmsUserId
FROM fs_company_user_mappings f
INNER JOIN (
    SELECT rmsUserId, MAX(id) as max_id
    FROM fs_company_user_mappings
    WHERE rmsUserId IN ({$userIdImp})
    GROUP BY rmsUserId
) g
ON f.rmsUserId = g.rmsUserId AND f.id = g.max_id;
");

        return $this->success($data);
    }
}
